import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Tag } from './entities/tag.entity';
import { CreateTagDto } from './dto/create-tag.dto';
import { UpdateTagDto } from './dto/update-tag.dto';

/**
 * 标签服务
 */
@Injectable()
export class TagsService {
  constructor(
    @InjectRepository(Tag)
    private tagsRepository: Repository<Tag>,
  ) {}

  /**
   * 创建标签
   */
  async create(createTagDto: CreateTagDto): Promise<Tag> {
    const tag = this.tagsRepository.create(createTagDto);
    return await this.tagsRepository.save(tag);
  }

  /**
   * 查询所有标签
   */
  async findAll(): Promise<Tag[]> {
    return await this.tagsRepository.find({
      relations: ['tools'],
    });
  }

  /**
   * 查询单个标签
   */
  async findOne(id: number): Promise<Tag> {
    const tag = await this.tagsRepository.findOne({
      where: { id },
      relations: ['tools'],
    });
    if (!tag) {
      throw new NotFoundException(`标签 #${id} 不存在`);
    }
    return tag;
  }

  /**
   * 更新标签
   */
  async update(id: number, updateTagDto: UpdateTagDto): Promise<Tag> {
    const tag = await this.findOne(id);
    Object.assign(tag, updateTagDto);
    return await this.tagsRepository.save(tag);
  }

  /**
   * 删除标签
   */
  async remove(id: number): Promise<void> {
    const tag = await this.findOne(id);
    await this.tagsRepository.remove(tag);
  }

  /**
   * 获取热门标签
   */
  async getPopular(limit = 20): Promise<Tag[]> {
    return await this.tagsRepository
      .createQueryBuilder('tag')
      .leftJoinAndSelect('tag.tools', 'tools')
      .loadRelationCountAndMap('tag.toolCount', 'tag.tools')
      .orderBy('toolCount', 'DESC')
      .take(limit)
      .getMany();
  }
}





